package com.wudizaba.microservicesdemosystem.config.MqttJob;

import com.alibaba.fastjson.JSONObject;
import com.wudizaba.microservicesdemocommon.constant.MqttConstant;
import com.wudizaba.microservicesdemosystem.module.po.DeviceData;
import com.wudizaba.microservicesdemosystem.service.IDeviceDataService;
import com.wudizaba.microservicesdemosystem.util.MqttUtils;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class DetectDeviceJob implements Job {

    @Autowired
    private IDeviceDataService deviceDataService;

    /**
     * 定时任务
     *
     * @param context
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        detectDeviceStatus();
    }

    //定时检测设备状态
    public void detectDeviceStatus() {
        List<DeviceData> list = deviceDataService.list();
        List<String> deviceIds = list.stream().map(DeviceData::getDeviceId).collect(Collectors.toList());
        String jsonString = JSONObject.toJSONString(deviceIds);
        System.out.println(jsonString);
        MqttUtils mqttUtils = new MqttUtils();
        MqttClient client = mqttUtils.createClient(MqttConstant.BROKER, MqttConstant.PUBLISH_CLIENT_ID, MqttConstant.USERNAME, MqttConstant.PASSWORD);
        mqttUtils.publishMessage(client, MqttConstant.TOPIC_DETECT_DEVICE, jsonString, MqttConstant.QoS_2);
    }


}
